<?php
class DB
{
	static private $_dbh;
	
	static public function init(array $db)
	{
		return self::getInstance($db);
	}
	
	static public function getInstance(array $db)
	{
		if (empty(self::$_dbh))
		{
			$dsn = 'mysql:host='.$db['hostname'].';dbname='.$db['database'];
			try 
			{
				self::$_dbh = new PDO($dsn, $db['username'], $db['password']);
				self::$_dbh->query("SET NAMES 'utf8'");
			} 
			catch (PDOException $e) 
			{
				print "Error!: " . $e->getMessage() . "<br/>";
				die();
			}
		}
	}
	
	static public function getDBH()
	{
		return self::$_dbh;
	}
	
	static public function fetch($sql, $params=array())
	{
		$sth = self::$_dbh->prepare($sql);
		if (count($params) > 0)
		{
			foreach($params as $key => $val)
			{
				$sth->bindValue(':'.$key, $val);
			}
		}
		$sth->execute();
		$result = $sth->fetch(PDO::FETCH_ASSOC);
		return $result;
	}
	
	static public function fetchAll($sql, $params=array())
	{
		$sth = self::$_dbh->prepare($sql);
		if (count($params) > 0)
		{
			foreach($params as $key => $val)
			{
				$sth->bindValue(':'.$key, $val);
			}
		}
		$sth->execute();
		$result = $sth->fetchAll(PDO::FETCH_ASSOC);
		return $result;
	}
	
	static public function insert($sql, $params=array())
	{
		$sth = self::$_dbh->prepare($sql);
		if (count($params) > 0)
		{
			foreach($params as $key => $val)
			{
				$sth->bindValue(':'.$key, $val);
			}
		}
		$ret = $sth->execute();
		$result = self::$_dbh->lastInsertId();;
		return $result;
	}
	
	static public function execute($sql, $params=array())
	{
		$sth = self::$_dbh->prepare($sql);
		if (count($params) > 0)
		{
			foreach($params as $key => $val)
			{
				$sth->bindValue(':'.$key, $val);
			}
		}
		$ret = $sth->execute();
		$count = $sth->rowCount();
		return $ret;
	}

}